package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.validation.constraints.Null;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

	@Autowired
	private UserAccountMapper userAccountMapper;

	@Autowired
	private UserAccountDetailMapper userAccountDetailMapper;

	/**
	 * 保存账户记录
	 * 幂等性处理：表中建立唯一索引userId
	 * @param userId
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void initAcount(Long userId) {
		// 1.新增用户账户记录
		UserAccount userAccount = new UserAccount();
		userAccount.setUserId(userId);
		BigDecimal giveAmount = new BigDecimal("10");
		userAccount.setTotalAmount(giveAmount);
		userAccount.setLockAmount(new BigDecimal("0"));
		userAccount.setAvailableAmount(giveAmount);
		userAccount.setTotalIncomeAmount(giveAmount);
		userAccount.setTotalPayAmount(new BigDecimal("0"));
		userAccountMapper.insert(userAccount);

		// 2.新增账户变动日志
		this.saveUserAcountDetail(userId,"充值赠送：" + giveAmount,SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,giveAmount, null);
	}

	@Override
	public void saveUserAcountDetail(Long userId, String title, String tradeType, BigDecimal amount, String orderNo) {
		UserAccountDetail userAccountDetail = new UserAccountDetail();
		userAccountDetail.setUserId(userId);
		userAccountDetail.setTitle(title);
		userAccountDetail.setTradeType(tradeType);
		userAccountDetail.setAmount(amount);
		userAccountDetail.setOrderNo(orderNo);
		userAccountDetailMapper.insert(userAccountDetail);
	}

	/**
	 * 获取当前用户账户可用余额
	 * @return
	 */
	@Override
	public BigDecimal getAvailableAmount() {
		// 1.获取当前用户id
		Long userId = AuthContextHolder.getUserId();

		// 2.根据用户ID查询账户记录
		LambdaQueryWrapper<UserAccount> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(UserAccount::getUserId,userId);
		UserAccount userAccount = userAccountMapper.selectOne(lambdaQueryWrapper);
		Assert.notNull(userAccount,"用户{}账户不存在",userId);
		// 3.返回可用余额
		return userAccount.getAvailableAmount();
	}

	/**
	 * 检查余额及扣减余额
	 * @param accountDeductVo 订单编号、扣减金额、购买内容、用户Id
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void checkAndDeduct(AccountDeductVo accountDeductVo) {

		// 1. 检查账户是否满足扣减需求，满足条件则完成账户扣减
		int count = userAccountMapper.checkAndDeduct(accountDeductVo.getUserId(),accountDeductVo.getAmount());
		if (count == 0){
			// 抛出异常则进行全局事务回滚
			throw new GuiguException(ResultCodeEnum.ACCOUNT_LESS);
		}

		// 2. 新增变更日志
		this.saveUserAcountDetail(accountDeductVo.getUserId(),accountDeductVo.getContent(),SystemConstant.ACCOUNT_TRADE_TYPE_MINUS,accountDeductVo.getAmount(),accountDeductVo.getOrderNo());

	}
}
